require "./base"
require "./binarystream"

class MDX < Base
	def initialize (file)
		super()
		
		puts "Loading #{file}"
		
		@stream = BinaryStream.new(file)
		@chunk = nil
		@list = ["VERS", "MODL", "SEQS", "GLBS", "TEXS", "MTLS", "GEOS"]
		
		parse()
	end
	
	def saveMDX (target)
		puts "Saving #{target}"
	end
	
	def saveMDL (target)
		puts "Saving #{target}"
	end
	
	def saveTXT (target)
		puts "Saving #{target}"
		
		File.open(target, "w") { |file|
			file.puts(@geos.geosets.size)
			
			@geos.geosets.each { |geoset|
				file.puts(geoset.vertexPositions.size)
				file.puts(geoset.faces.size)
				
				texture = @texs.textures[@mtls.materials[geoset.materialId].layerChunk.layers[0].textureId].fileName
				
				if texture == ""
					file.puts("None")
				else
					file.puts(texture)
				end
				
				geoset.vertexPositions.each { |vertexPosition|
					file.puts(vertexPosition.to_t)
				}
				
				geoset.vertexNormals.each { |vertexNormal|
					file.puts(vertexNormal.to_t)
				}
				
				geoset.vertexTexturePositions.each { |texturePosition|
					file.puts(texturePosition.to_t)
				}
				
				geoset.faces.each { |face|
					file.puts(face.to_t)
				}
			}
		}
	end
	
	def info ()
		puts "Info of #{self}:"
		p @mtls
	end
	
	private
	
	def parse ()
		@stream.readExpect("MDLX")
		
		while chunk = @stream.readChunk()
			if @list.include?(chunk.token)
				puts "reading chunk #{chunk.token}"
				
				case chunk.token
					when "VERS" then @vers = VersionChunk.new(@stream)
					when "MODL" then @modl = ModelChunk.new(@stream)
					when "SEQS" then @seqs = SequenceChunk.new(@stream, chunk.size)
					when "GLBS" then @glbs = GlobalSequenceChunk.new(@stream, chunk.size)
					when "MTLS" then @mtls = MaterialChunk.new(@stream, chunk.size)
					when "TEXS" then @texs = TextureChunk.new(@stream, chunk.size)
					when "GEOS" then @geos = GeosetChunk.new(@stream, chunk.size)
					else raise "This will never be shown"
				end
			else
				puts "skipping chunk #{chunk.token}"
				@stream.skip(chunk.size)
			end
		end
	end
end